package com.itheima.web;

import com.itheima.bean.User;
import com.itheima.common.R;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
        String phone = map.get("phone");
        String code = (String) redisTemplate.opsForValue().get(phone);
        if (!code.equalsIgnoreCase(map.get("code"))) {
            return R.error("验证码错误!");
        }
        User user = userService.findLogin(phone);
        if (user == null) {
            user = new User();
            user.setName(code);
            user.setPhone(phone);
            user.setStatus(1);
            userService.add(user);
        }
        session.setAttribute("user",user);
        redisTemplate.delete(phone);
        return R.success(user);
    }

    @PostMapping("/loginout")
    public R loginOut(HttpSession session){

        try {

            session.removeAttribute("user");

            session.invalidate();

            return R.success("退出成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("退出失败!");
        }

    }
}
